<template>
	<view class="container">
		<view class="example">
			<uni-forms ref="form" :model="form" labelWidth="80px">
				<uni-forms-item label="采购订单" name="purchase_id" required>					
					<uni-data-select v-model="form.purchase_id" :localdata="purchaseOptions" 
					@change="chagePurchase"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="资产编码" name="num" required>				
					<uni-easyinput suffixIcon="scan" v-model="form.num" placeholder="请扫码或输入"
					trim="both" @iconClick="doScan()"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item label="仓库" name="house_id" required>					
					<uni-data-select v-model="form.house_id" :localdata="houseOptions" 
					@change="chagePurchase"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="入库说明" name="remark" required>
					<uni-easyinput v-model="form.remark" type="textarea" autoHeight 
					placeholder="请输入详细说明" />
				</uni-forms-item>
				<uni-forms-item label="入库图片" name="imgs">
					<view class="uni-list list-pd">
						<view class="uni-list-cell cell-pd">
							<view class="uni-uploader">
								<view class="uni-uploader-body">
									<view class="uni-uploader__files">
										<block v-for="(image,index) in imagePreList" :key="index">
											<view class="uni-uploader__file">
												<image class="uni-uploader__img" :src="image" :data-src="image" 
													@longpress="imageAction(index)" @tap="previewImage"></image>
											</view>
										</block>
										<view class="uni-uploader__input-box">
											<view class="uni-uploader__input" @tap="chooseImage"></view>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</uni-forms-item>
			</uni-forms>
			<button type="primary" @click="save">保存</button>
		</view>
	</view>
</template>

<script>
	import { handleTree, parseTime	} from '@/api/sys.js'
	import upload from '@/utils/upload'
	import { apiGet, apiPost, apiPut, apiDs	} from '@/api/openapi'

	export default {
		data() {
			return {
				form: {},
				rules: {
					purchase_id: {
						rules: [{
							required: true,
							errorMessage: '采购单不能为空'
						}]
					},
					house_id: {
						rules: [{
							required: true,
							errorMessage: '仓库不能为空'
						}]
					},
					num: {
						rules: [{
							required: true,
							errorMessage: '编号不能为空'
						}]
					}
				},
				purchaseOptions:[],
				houseOptions: [],
				//可选的最多图片数
				imageSize:9,
				imageList: [],
				imagePreList:[]
			}
		},
		onLoad() {
			this.getPurchases();
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			getPurchases() {
				let params = {
					"asset_purchase": {"@column":"id:value,model_id,dept_id", "@alias":"t", "apply_status":'4'},
					"asset_model": {"@alias":"m", "@column":"name:text,price","@join":"m.id = t.model_id"},
					"@pager":{"page":1,"limit":1000}
				};
				apiGet(params).then(response => {
					this.purchaseOptions = response.data.rows;
				})
				
				let houseParams = {
					"@column":"id:value,name:text", 
					"@table":"asset_warehouse", 
					"status":'1',
					"@pager":{"page":1,"limit":1000}
				};
				apiGet(houseParams).then(response => {
					this.houseOptions = response.data.rows;
				})
			},
			// 扫码操作
			doScan(){
				uni.scanCode({
					scanType: ['barCode', 'qrCode'],
					success: function (res) {
						this.form.num = res.result;
					}
				});
			},
			reset() {
				this.form = {
					id: null,
					purchase_id: null,
					model_id: null,
					house_id: null,
					num: null,
					imgs: null,
					status:'1',
					dept_id: null,
					buy_time:'@now()',
					comment: null
				};
				this.imageList = [];
				this.imagePreList = [];
			},
			chagePurchase(e) {
				for(var i=0;i<this.purchaseOptions.length;i++){
					if(this.purchaseOptions[i].value == this.form.purchase_id){
						this.form.model_id = this.purchaseOptions[i].model_id;
						this.form.price = this.purchaseOptions[i].price;
						this.form.dept_id = this.purchaseOptions[i].dept_id;
					}
				}
			},
			save(ref) {
				this.$refs.form.validate().then(res => {
					this.form.imgs = this.imageList.join(',')
					let data = {"@tags": ['asset_info', 'asset_in']};
					data['asset_info'] = this.form;
					data['asset_in'] = {
						"asset_id":"@asset_info.id",
						"imgs":this.form.imgs,
						"type": '1',
						"asset_num": this.form.num,
						"house_id": this.form.house_id,
						"remark": this.form.comment
					};
					apiPost(data).then(response => {
					  this.$modal.msgSuccess("操作成功");
					  this.reset();
					});			
				});
			},
			// 选择图片并上传
			chooseImage: async function() {
				if (this.imageList.length === 9) {
					let isContinue = await this.isFullImg();
					console.log("是否继续?", isContinue);
					if (!isContinue) {
						return;
					}
				}
				uni.chooseImage({
					sourceType: ['camera', 'album'],
					sizeType: ['compressed', 'original'],
					count:  this.imageSize - this.imageList.length,
					success: (res) => {
						res.tempFilePaths.forEach(f=>{
							upload({
							  url: '/common/upload',
							  filePath: f
							}).then( resf => {
								this.imageList.push(resf.fileName);
								this.imagePreList.push(resf.url);
							});
						})
					},
					fail: (err) => {	
					  this.$modal.msgSuccess("选择图片失败： " + err);
					}
				})
			},
			isFullImg: function() {
				return new Promise((res) => {
					uni.showModal({
						content: "已经有9张图片了,是否清空现有图片？",
						success: (e) => {
							if (e.confirm) {
								this.imageList = [];
								res(true);
							} else {
								res(false)
							}
						},
						fail: () => {
							res(false)
						}
					})
				})
			},
			// 预览图片
			previewImage: function(e) {
				var current = e.target.dataset.src
				uni.previewImage({
					current: current,
					urls: this.imagePreList
				})
			},
			// 图片上长按的操作
			imageAction: function(index){
				if(this.action == 'view'){
					return;
				}
				uni.showModal({
					content: "您想要删除选中的图片吗？",
					success: (e) => {
						if (e.confirm) {
							this.imageList.splice(index,1);
							this.imagePreList.splice(index,1);
						}
					},
					fail: () => {
						res(false)
					}
				})
			},
			// 验证设备权限
			async checkPermission(code) {
				let type = code ? code - 1 : this.sourceTypeIndex;
				let status = permision.isIOS ? await permision.requestIOS(sourceType[type][0]) :
					await permision.requestAndroid(type === 0 ? 'android.permission.CAMERA' :
						'android.permission.READ_EXTERNAL_STORAGE');

				if (status === null || status === 1) {
					status = 1;
				} else {
					uni.showModal({
						content: "没有开启权限",
						confirmText: "设置",
						success: function(res) {
							if (res.confirm) {
								permision.gotoAppSetting();
							}
						}
					})
				}

				return status;
			}
		}
	}
</script>


<style lang="scss">
	page {
		background-color: #ffffff;
	}

	.example {
		padding: 15px;
		background-color: #fff;
	}

	.segmented-control {
		margin-bottom: 15px;
	}

	.button-group {
		margin-top: 15px;
		display: flex;
		justify-content: space-around;
	}

	.form-item {
		display: flex;
		align-items: center;
		flex: 1;
	}

	.button {
		display: flex;
		align-items: center;
		height: 35px;
		line-height: 35px;
		margin-left: 10px;
	}
	
	.cell-pd {
		padding: 22rpx 10rpx;
	}

	.list-pd {
		margin-top: 10rpx;
	}
	
	/* 上传 */
	.uni-uploader {
		flex: 1;
		flex-direction: column;
	}
	.uni-uploader-head {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
	}
	.uni-uploader-info {
		color: #B2B2B2;
	}
	.uni-uploader-body {
		margin-top: 16rpx;
	}
	.uni-uploader__files {
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
	}
	.uni-uploader__file {
		margin: 10rpx;
		width: 210rpx;
		height: 210rpx;
	}
	.uni-uploader__img {
		display: block;
		width: 210rpx;
		height: 210rpx;
	}
	.uni-uploader__input-box {
		position: relative;
		margin:10rpx;
		width: 208rpx;
		height: 208rpx;
		border: 2rpx solid #D9D9D9;
	}
	.uni-uploader__input-box:before,
	.uni-uploader__input-box:after {
		content: " ";
		position: absolute;
		top: 50%;
		left: 50%;
		-webkit-transform: translate(-50%, -50%);
		transform: translate(-50%, -50%);
		background-color: #D9D9D9;
	}
	.uni-uploader__input-box:before {
		width: 4rpx;
		height: 79rpx;
	}
	.uni-uploader__input-box:after {
		width: 79rpx;
		height: 4rpx;
	}
	.uni-uploader__input-box:active {
		border-color: #999999;
	}
	.uni-uploader__input-box:active:before,
	.uni-uploader__input-box:active:after {
		background-color: #999999;
	}
	.uni-uploader__input {
		position: absolute;
		z-index: 1;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		opacity: 0;
	}
</style>